#include "ScreenshotHelper.h"
#include <QQuickWindow>
#include <QStandardPaths>
#include <QFileDialog>
#include <QClipboard>
#include <QDebug>
#include "src/confighelper.h"
#include <QQmlApplicationEngine>

ScreenshotHelper::ScreenshotHelper(QObject *parent)
    : QObject{parent}
{
    engine = nullptr;
    targetObject = nullptr;

    fullScreenHotkey = new QHotkey(this);
    selectionHotkey = new QHotkey(this);
    updateHotKey();

    QObject::connect(fullScreenHotkey, &QHotkey::activated, this, &ScreenshotHelper::fullScreenShot);
    QObject::connect(selectionHotkey, &QHotkey::activated, this, &ScreenshotHelper::selectionShot);
}

void ScreenshotHelper::setEngine(QQmlApplicationEngine *ptr)
{
    engine = ptr;
}

void ScreenshotHelper::fullScreenShot()
{
    saveImageToClipboard(0, 0);
}

void ScreenshotHelper::selectionShot()
{
    if (engine)
    {
        if (!targetObject)
        {
            const QUrl url(QStringLiteral("qrc:/qml/qml/Screenshot.qml"));
            engine->load(url);
            foreach (QObject* rootObject, engine->rootObjects())
            {
                if (rootObject->objectName() == "screenshot")
                {
                    targetObject = rootObject;
                    break;
                }
            }
        }
        else
        {
            QMetaObject::invokeMethod(targetObject, "screenshotInit");
            targetObject->setProperty("visible", true);
        }
    }
}

void ScreenshotHelper::saveImageToClipboard(int x, int y, int width, int height)
{
    auto screen = QApplication::primaryScreen();
    auto pixmap = screen->grabWindow(0, x, y, width, height);

    auto clipboard = QApplication::clipboard();
    if (clipboard)
    {
        clipboard->setPixmap(pixmap);
    }
}

void ScreenshotHelper::saveImageToFile(QString filePath, QString nameFilter)
{
    // 处理文件扩展名
    QFileInfo fileinfo(filePath);
    QString suffix = fileinfo.suffix().toLower();
    if(!(suffix == "png" || suffix == "jpg" || suffix == "jpeg" || suffix == "bmp"))
    {
        if(nameFilter == "png图像 (*.png)")
            filePath += ".png";
        else if(nameFilter == "jpg图像 (*.jpg)")
            filePath += ".jpg";
        else if(nameFilter == "jpeg图像 (*.jpeg)")
            filePath += ".jpeg";
        else if(nameFilter == "bmp图像 (*.bmp)")
            filePath += ".bmp";
        else
            filePath += ".png";
    }
    auto clipboard = QApplication::clipboard();
    if (clipboard)
    {
        auto pixmap = clipboard->pixmap();
        pixmap.save(filePath);
    }
}

void ScreenshotHelper::updateHotKey() {
    // 读取配置文件
    QString key_1 = Confighelper::getInstance()->readIniFile("FullScreen");
    QString key_2 = Confighelper::getInstance()->readIniFile("Selection");
    fullScreenHotkey->setShortcut(QKeySequence(key_1), true);
    selectionHotkey->setShortcut(QKeySequence(key_2), true);
}
